<?php

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;

class Comment extends Base
{
    /**
     * 禁止被批量赋值的字段
     *
     * @var array
     */
    protected $guarded = [];

    // 软删除
    use SoftDeletes;

    private $child = [];

    /**
     * 关联文章表
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function article(){
        return $this->belongsTo(Article::class);
    }

    public function user()
    {
        return $this->belongsTo(OauthUser::class, 'oauth_user_id');
    }

    public function storeData($data){

        //根据是否有id判断修改还是添加
        if(isset($data['id'])&&$data['id']){
            $result=$this->where('id',$data['id'])->update($data);
        }else{
            $result=$this->create($data);
        }
        return $result;
    }

    /**
     * @param $article_id 文章id
     * @return mixed 该文章所有评论
     */
    public function getCommentByArticleId($article_id){
        //顶级评论
        $pcomments=$this->select("comments.*","o.name","o.avatar")
            ->join("oauth_users as o","o.id","comments.oauth_user_id")
            ->where("comments.article_id",$article_id)
            ->where("comments.pid",0)
            ->orderBy("created_at","desc")
            ->get()
            ->toArray();

        foreach ($pcomments as $k=>$v){
            $this->child=[];
            $this->getSonComment($v);
            foreach ($this->child as $ck=>$cv){
                $reply_id=$this->where('id', $cv['pid'])->value('oauth_user_id');
                //查找被回复的用户名
                $reply_name=OauthUser::where("id",$reply_id)->value("name");
                $this->child[$ck]['reply_name']=$reply_name;
            }

            $pcomments[$k]['child']=$this->child;
        }
        return $pcomments;
    }

    /**
     * 获取顶级评论下的所有评论
     * @param $data 单条的顶级评论(pid=0）
     */
    public function getSonComment($data){
            $comments=$this->select("comments.*","o.name","o.avatar")
                ->join("oauth_users as o","o.id","comments.oauth_user_id")
                ->where("comments.pid",$data['id'])
                ->orderBy("created_at","asc")
                ->get()
                ->toArray();

            if($comments){
                foreach ($comments as $k=>$v){
                    $this->child[]=$v;
                    $this->getSonComment($v);
                }
            }
    }


}
